<template>
  <div class="topbar">
    <!-- 版心 -->
    <div class="wrap wrapTopbar">
      <!-- 左侧标题 -->
      <div class="l">欢迎来到叩丁狼积分商城</div>
      <!-- 右侧菜单 -->
      <ul class="r">
        <li>
          <img :src="userInfo.headImg" class="avator" alt="" />
          用户名：{{ userInfo.nickName }}
        </li>
        <li>我的积分：{{ userInfo.coin }}</li>
        <li>获取积分</li>
        <li>叩丁狼官网</li>

        <li class="cart-btn" v-if="isLogined">
          <img src="../assets/img/cart.png" alt="" />
          <span>购物车</span>
          <strong>{{ cartTotal }}</strong>
        </li>

        <li class="login-btn" @click="changeIsShowLoginModal(true)" v-else>
          登录
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import { WeixinLoginApi } from "@/request/api";
import { mapActions, mapMutations, mapState } from "vuex";
export default {
  data() {
    return {};
  },
  //钩子函数
  created() {
    //只要用户扫码，页面也重新刷新，此时可以获取下code值
    //有可能获取不到code $nextTick()
    this.$nextTick(async () => {
      console.log("this.$route", this.$route.query.code);
      let mycode = this.$route.query.code;
      //当地址栏中没有获取到code时
      if (!mycode) {
        //获取token
        let mytoken = localStorage.getItem("x-auth-token");
        this.chanIsLogined(Boolean(mytoken));
        if (mytoken) {
          console.log("更新用户信息");
          this.asyncChangeUserInfo();
        } else {
          console.log("初始化。。。");
          this.initUserInfo();
        }
        return;
      }
      let res = await WeixinLoginApi({
        //当有code时，就可以发送微信扫码登录请求
        code: mycode,
      });
      console.log("WeixinLoginApi", res);
      if (res.code == 0) {
        //1.提示登录成功
        // alert("登录成功");
        this.asyncIsShowToast({
          msg: "登录成功",
          type: "success", //提示图标类型
        });
        //2.存储token
        localStorage.setItem("x-auth-token", res["x-auth-token"]);
        //3改变登录状态 （切换购物车显示）
        this.chanIsLogined(true);
        // 4.获取用户信息
        this.asyncChangeUserInfo();
      } else if (res.code == 400) {
        //提示用户重新扫码
        //1. 提示二维码失效
        // alert("请重新扫码二维码");
        this.asyncIsShowToast({
          msg: "请重新扫码二维码",
          type: "denger", //提示图标类型
        });
        //2. 把登录模态框打开
        this.changeIsShowLoginModal(true);
      } else if ((res.code = 407)) {
        //提升用户再使用手机号验证码登录一次
        // alert("请使用手机号验证码登录一次");
        this.asyncIsShowToast({
          msg: "请使用手机号验证码登录一次",
          type: "denger", //提示图标类型
        });
        //把登录模态框打开
        this.changeIsShowLoginModal(true);
        //存储uuid（登录时取）
        localStorage.setItem("uuid", res.uuid);
      }
    });
  },
  computed: {
    ...mapState({
      isLogined: (state) => state.loginStatus.isLogined,
      cartTotal: (state) => state.userInfo.cartTotal,
      userInfo: (state) => state.userInfo.userInfo,
    }),
  },
  watch: {
    //通过监听路由方式，切换登录状态
    // "$route.path": {
    //   handler(newVal, oldVal) {
    //     console.log("$route.path", newVal, oldVal);
    //     //路由地址变化后，判断当前用户token是否还存在
    //     //如果存在更新登录状态就为true
    //     //如果不存在更新登录状态为false
    //     let mytoken = localStorage.getItem("x-auth-token");
    //     // if (mytoken) {
    //     //   this.chanIsLogined(true);
    //     // } else {
    //     //   this.chanIsLogined(false);
    //     // }
    //     this.chanIsLogined(Boolean(mytoken));
    //   },
    // },
  },
  methods: {
    ...mapMutations({
      changeIsShowLoginModal: "showModal/changeIsShowLoginModal",
      chanIsLogined: "loginStatus/chanIsLogined",
      initUserInfo: "userInfo/initUserInfo",
    }),
    ...mapActions({
      asyncChangeUserInfo: "userInfo/asyncChangeUserInfo",
      asyncIsShowToast: "showToast/asyncIsShowToast",
    }),
  },
};
</script>

<style lang="less" scoped>
.topbar {
  height: 40px;
  background: #242b39;
  font-size: 14px;
  font-family: SourceHanSansSC;
  font-weight: 300;
  color: #fffefe;
  line-height: 40px;
  .wrapTopbar {
    display: flex;
    justify-content: space-between;
    .r {
      li {
        float: left;
        margin-left: 20px;
        cursor: pointer;
        text-align: center;
        &.login-btn {
          width: 124px;
          height: 40px;
          background: #0a328e;
        }
        &.cart-btn {
          width: 124px;
          height: 40px;
          background: #0a328e;
          text-align: center;
          img {
            width: 20px;
            height: 19px;
            vertical-align: middle;
          }
          span {
            margin: 0 8px;
          }
          strong {
            width: 22px;
            height: 22px;
            line-height: 22px;
            display: inline-block;
            border-radius: 50%;
            background-color: #fd604d;
          }
        }
      }
      .avator {
        width: 22px;
        vertical-align: middle;
        border-radius: 50%;
      }
    }
  }
}
</style>
